package com.bang.study.esl.runner;

import lombok.extern.slf4j.Slf4j;
import org.freeswitch.esl.client.outbound.IClientHandlerFactory;
import org.freeswitch.esl.client.outbound.SocketClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.Timer;
import java.util.TimerTask;


/**
 * ESL outbound
 */
@Slf4j
@Component
@Scope("singleton")
public class EslOutboundServer implements ApplicationRunner {

    @Value("${freeswitch.outbound.hostname}")
    private String hostname;

    @Value("${freeswitch.outbound.port}")
    private Integer port;

    @Autowired
    private IClientHandlerFactory eslOutBoundListener;


    private SocketClient socketClient;

    @Override
    public void run(ApplicationArguments args) {
        socketClient = new SocketClient(new InetSocketAddress(hostname, port), eslOutBoundListener);
        socketClient.startAsync();
        log.error("[SocketClient] 连接成功>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.error("[SocketClient] 连接成功>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.error("[SocketClient] 连接成功>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    }

    /**
     * 检测ESL连接状态
     */
    public void testEslConnStatus() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {

                if (!status()) {
                    printOutboundEslConnErrMsg();
                }
            }
        }, 10000);
    }

    /**
     * Outbound Server 运行状态
     *
     * @return
     */
    public boolean status() {
        if (null != socketClient) {
            return socketClient.isRunning();
        }
        return false;
    }

    /**
     * 打印OutboundESL连接异常信息
     */
    private void printOutboundEslConnErrMsg() {
        log.error("->");
        log.error("->");
        log.error("->");
        log.error("->");
        log.error("->");
        log.error("[ERR]->OutboundESL连接异常,原因可以如下:");
        log.error("[ERR]->1. Outbound ESL端口被占用.");
        log.error("[ERR]->2. Outbound ESL连接信息不正确.");
        log.error("<-");
        log.error("<-");
        log.error("<-");
        log.error("<-");
        log.error("<-");
        System.exit(-1);
    }


}